package cn.yougou.serviceImpl;

import cn.yougou.common.DtoUtil;
import cn.yougou.common.OrderUtils;
import cn.yougou.dto.Dto;
import cn.yougou.mapper.YgOrderMapper;
import cn.yougou.pojo.YgBill;
import cn.yougou.pojo.YgOrder;
import cn.yougou.pojo.YgUser;
import cn.yougou.pojo.YgUserCoupons;
import cn.yougou.service.YgUserCouponsService;
import cn.yougou.service.shopcart.YgBillService;
import cn.yougou.service.shopcart.YgCommodityProductService;
import cn.yougou.service.shopcart.YgCommodityService;
import cn.yougou.service.user.YgOrderService;
import cn.yougou.service.user.YgUserService;
import cn.yougou.vo.*;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @auth 韩帅锋
 * @date 2020/12/7 15:49
 */
@Service
public class YgUserOrderServiceImpl implements YgOrderService {

    @Reference(check = false)
    YgUserCouponsService ygUserCouponsService;

    @Reference(check = false)
    private YgCommodityService ygCommodityService;

    @Reference(check = false)
    private YgCommodityProductService ygCommodityProductService;

    @Autowired
    YgBillService ygBillService;

    @Autowired
    private YgOrderMapper ygOrderMapper;

    @Autowired
    private YgUserService ygUserService;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    @Override
    public int updateOrder(YgOrderVo ygOrderVo) {
        return ygOrderMapper.updateOrder(ygOrderVo);
    }

    @Override
    public List<YgOrderVo> selCondition(YgOrderVo ygOrderVo) {
        //修改日期格式
        List<YgOrderVo> list = ygOrderMapper.selCondition(ygOrderVo);
        for (YgOrderVo listVo : list) {
            Date da = listVo.getCreatedate();
            String s = sdf.format(da);
            listVo.setQcreatedate(s);
        }
        return  list;
    }

    @Override
    public int deleteById(YgOrderVo ygOrderVo) {
        int id = ygOrderVo.getId();
        return ygOrderMapper.deleteById(id);
    }

    @Override
    public Integer getOkOrder(Integer ygUserid) {
        return ygOrderMapper.getOkOrder(ygUserid);
    }

    /**
     * 根据状态查询订单信息
     * Condition:状态.
     */
    @Override
    public List<YgOrder> queryCondition(YgOrder orderstatus) {
        return ygOrderMapper.queryCondition(orderstatus);
    }


    /**
     * 查询订单表全部数据..
     * @return
     */
    @Override
    public List<YgOrder> queryOrderAll() {
        return ygOrderMapper.queryOrderAll();
    }

    /**
     * 新增订单
     * */
    public Dto createOrder(YgResOrderVo ygResOrderVo) {
        //订单id集合
        List orderIdList = new ArrayList<>();
        //获取商品列表
        YgResCommodityVo[] ygResCommodityVos = ygResOrderVo.getYgResCommodityVos();
        if (ygResCommodityVos.length != 0) {
            //调用服务判断商品数组是否还有库存
            Dto resultDto = ygCommodityProductService.isItSoldOut(ygResCommodityVos);
            //判断库存是否不足，如果不足直接return
            if(resultDto.getMsg().equals("inventoryShortage")){
                return resultDto;
            }else if(resultDto.getMsg().equals("adequateInventory")){
                //商品库存足够再新增订单
                orderIdList = this.generateOrders(ygResOrderVo);
                resultDto.setData(orderIdList);
                //返回订单id集合
                return resultDto;
            }
        }
        return null;
    }

    /**
     * 生成订单
     * @param ygResOrderVo
     * @return
     */
    public List generateOrders(YgResOrderVo ygResOrderVo){
        List result = new ArrayList<>();
        //获取到商品数组的VO
        YgResCommodityVo[] ygResCommodityVos = ygResOrderVo.getYgResCommodityVos();
        for (int i = 0; i < ygResCommodityVos.length; i++) {
            //获取订单编号
            String OrderCode = OrderUtils.getOrderCode(ygResOrderVo.getUserid());
            YgOrder ygOrder = new YgOrder(
                    ygResOrderVo.getUserid(),
                    ygResOrderVo.getPhone(),
                    ygResOrderVo.getAddress(),
                    ygResOrderVo.getMessage(),
                    OrderCode,
                    1,
                    ygResCommodityVos[i].getCommodityCount() * ygResCommodityVos[i].getCommodityDouble(),
                    0.0,
                    0.0,
                    new Date(),
                    new Date(),
                    -1,
                    ygResCommodityVos[i].getId(),
                    ygResCommodityVos[i].getCommodityCount(),
                    ygResCommodityVos[i].getSpecifications(),
                    ygResCommodityVos[i].getProductid(),
                    ygResCommodityVos[i].getCommodityDouble()
            );
            ygOrderMapper.insert(ygOrder);
            result.add(ygOrder.getId());
        }
        return result;
    }

    /**
     * 余额支付
     * */
    @Override
    public boolean balancePayment(YgPaymentVo ygPaymentVo) {
        //1 获取实付款
        YgResOrderVo ygResOrderVo = ygUserCouponsService.getOrderYgResOrderVo(ygPaymentVo);
        //2 判断用户账户余额是否满足实付款
        boolean config = determineUserBalance(ygPaymentVo.getUserId(),ygResOrderVo.getActualprice());
        if(config){
            //3 修改订单状态为 5:代发货 !!!待更改  &  获取订单List
            List<YgOrder> orderList = new ArrayList<> ();
            YgOrderVo ygOrderVo = new YgOrderVo();
            for(Integer orderId : ygPaymentVo.getOrderIdArr()){
                //获取订单List
                orderList.add(ygOrderMapper.queryById(orderId));
                //修改订单状态
                ygOrderVo.setId(orderId);
                ygOrderVo.setOrderstatus(2);
                ygOrderMapper.updateOrder(ygOrderVo);
            }
            //4 调用商品表，商品规格表 减库存加销量服务
            boolean change = ygCommodityService.placeOrder(orderList);
            //5 用户优惠券表更改状态为2，如果使用了优惠券改，没使用就不改
            if(ygPaymentVo.getCouponsId() != null){
                YgUserCoupons ygUserCoupons = new YgUserCoupons();
                ygUserCoupons.setId(ygPaymentVo.getCouponsId());
                ygUserCoupons.setState(2);
                ygUserCouponsService.update(ygUserCoupons);
            }
            //6 更新用户账户余额
            YgUser ygUser = new YgUser();
            ygUser.setId(ygPaymentVo.getUserId());
            ygUser.setMoney(ygResOrderVo.getActualprice());
            ygUserService.reduceBalance(ygUser);
            //7 账单表相对应增加数据
            ygBillService.insert(new YgBill(
                    ygResOrderVo.getOrderDate(),   //订单详情
                    ygPaymentVo.getCouponsId(),    //优惠券id
                    new Date(),                    //当前时间
                    ygPaymentVo.getModeOfPayment(), //支付方式
                    ygResOrderVo.getActualprice()//实付款
            ));
        }else{
            return false;
        }
        return true;
    }

    /**
     * 判断用户账户余额是否满足订单金额
     * 用户id  实付款
     * @return
     */
    public boolean determineUserBalance(Integer userId,double actualprice){
        //1 获取用户余额
        double userMoney = ygUserService.queryById(userId).getMoney();
        //2 判断账户余额是否足够
        if(userMoney < actualprice){
            return  false;
        }
        return true;
    }

    /**
     *微信支付
     * */
    @Override
    public boolean weixin(YgPaymentVo ygPaymentVo) {
        return true;
    }

    /**
     *支付宝支付
     * */
    @Override
    public boolean zhifubao(YgPaymentVo ygPaymentVo) {
        return true;
    }





}
